package com.xxl.job.admin.core.conf;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.xxl.job.admin.core.util.TenantContextUtil;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 增加多租户拦截器
 *
 * @author chenlinqing
 * @description:
 * @date: 2025/7/28 11:36
 */
@Component
public class XxlJobTenantHandler implements TenantLineHandler {
    @Override
    public Expression getTenantId() {
        if (StringUtils.hasLength(TenantContextUtil.getTenantId())) {
            return new StringValue(TenantContextUtil.getTenantId());
        } else {
            return null;
        }

    }

    @Override
    public String getTenantIdColumn() {
        return "tenant_id";
    }

    @Override
    public boolean ignoreTable(String tableName) {
        //租户表，默认忽略
        if ("xxl_job_tenant".equals(tableName)
                || "xxl_job_log_detail".equals(tableName)
                || "xxl_job_admin_machine".equals(tableName)) {
            return true;
        }
        //如果有租户ID，则所有表生效。本系统管理员租户能看到所有数据
        if (StringUtils.hasLength(TenantContextUtil.getTenantId())) {
            return false;
        } else {
            return true;
        }
    }

}
